#include "Button.h"
#include "../Core/Point2.h"
#include "../Core/glExt.h"
#include "../Core/GlPlatform.h"

namespace Gui {
	Button::Button() : Widget( Core::Rect2f(0,0,0,0) ) {
	}

	Button::Button( const Core::Rect2f& rect, std::function<void()> fn, const Core::Color4& bgColor, const Core::Color4& fgColor, const Core::Color4& pressedColor, const std::string& caption )
		: Widget( rect ), onClick(fn), textColor(fgColor), caption(caption), pressedColor(pressedColor), pressed(false) {
		this->mColor = bgColor;
	}

	bool Button::onMouseDown( const Core::Point2f& pt ) {
		if ( mClientArea.test( pt ) ) {
			onClick();
			pressed = true;
			return true;
		}
		return false;
	}

	bool Button::onMouseUp( const Core::Point2f& pt ) {
		pressed = false;
		return false;
	}

	void Button::render() {
		using namespace Core;
		glBegin( GL_QUADS ); {
			glExt::emitColor( pressed ? pressedColor : mColor );
			mClientArea.eachCorner( Core::glExt::emitVertex2<float> );
		} glEnd();

		glExt::emitColor( textColor );
		Point2f pos = mClientArea.center();
		pos.x -= (caption.length()*8)/2;
		pos.y += 13 / 2;
		glRasterPos2f( pos.x, pos.y );
		for ( size_t idx = 0, len = caption.length(); idx < len; ++idx )
			glutBitmapCharacter( GLUT_BITMAP_8_BY_13, caption[idx] );
	}
}